package com.tanhua.dubbo.api.mongo;

import com.tanhua.model.mongo.UserLocation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 搜附近
 */
@DubboService
@Slf4j
public class UserLocationApiImpl implements UserLocationApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 上报地理位置
     *
     * @param userId
     * @param longitude
     * @param latitude
     * @param address
     * @return
     */
    @Override
    public void reportLocation(Long userId, Double longitude, Double latitude, String address) {
        //1根据当前用户id查询地理位置是否存在
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);
        long nowTime = System.currentTimeMillis();
        //2如果存在 更新当前用户位置
        if(userLocation != null){
            log.debug("*************更新了******************");
            Update update = new Update();
            update.set("location",new GeoJsonPoint(longitude,latitude)); //x:经度（longitude） y:纬度（latitude）
            update.set("address",address);
            update.set("updated",nowTime);
            mongoTemplate.updateFirst(query,update,UserLocation.class);
        }else {
            log.debug("*************新增了******************");
            //3如果不存在 直接保存用户位置
            userLocation = new UserLocation();
            userLocation.setUserId(userId);//当前用户id
            userLocation.setLocation(new GeoJsonPoint(longitude,latitude));//经纬度
            userLocation.setAddress(address);
            userLocation.setCreated(nowTime);
            userLocation.setUpdated(nowTime);
            mongoTemplate.insert(userLocation);
        }
    }

    /**
     * 根据当前用户id和距离搜索userLocation表附近的用户数据
     *
     * @param userId
     * @param distance
     * @return
     */
    @Override
    public List<Long> searchNearBy(Long userId, Long distance) {
        log.debug("*************搜附近***userId***{}******distance***{}***",userId,distance);
        //1.根据当前用户id查询用户位置
        Query query1 = new Query();
        query1.addCriteria(Criteria.where("userId").is(userId));
        UserLocation userLocation = mongoTemplate.findOne(query1, UserLocation.class);
        GeoJsonPoint location = userLocation.getLocation();//当前用户位置 经纬度
        //2.根据当前用户位置与搜索距离与排除自己进行搜索
        Query query2 = new Query();
        //Point:当前用户位置  Distance：搜索距离 传入distance单位：米 转为 千米
        Distance radius = new Distance(distance/1000, Metrics.KILOMETERS);//double value, Metric metric
        Circle circle = new Circle(location,radius);
        query2.addCriteria(Criteria.where("location").withinSphere(circle).and("userId").ne(userId));
        List<UserLocation> userLocationList = mongoTemplate.find(query2, UserLocation.class);
        log.debug("*************userLocationList*******************"+userLocationList.size());
        //3.基于搜索的结果得到附近用户ids(包含性别不满足的用户ids)
        if(!CollectionUtils.isEmpty(userLocationList)){
            return userLocationList.stream().map(UserLocation::getUserId).collect(Collectors.toList());
        }
        return null;
    }
}
